package com.renren.project.core.utils;

import com.google.common.collect.Maps;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Date;
import java.util.Map;

/**
 * jwt工具类
 */
@ConfigurationProperties(prefix = "renren.jwt")
@Component
@Slf4j
public class JwtUtils {

    // 签名是有谁生成
    private static final String ISSUSER = "LITEMALL";
    // 签名的主题
    private static final String SUBJECT = "this is litemall token";
    // 签名的观众
    private static final String AUDIENCE = "MINIAPP";

    //private String secret;
    private long expire;
    private String header;

    public String generateToken(Map<String, Object> map, PrivateKey key, Date expireDate) throws Exception {
        if(expireDate == null){
            Date nowDate = new Date();
            expireDate = new Date(nowDate.getTime() + expire * 1000);
        }
        Map<String, Object> headerMap = Maps.newHashMap();
        headerMap.put("alg", "RS256");
        headerMap.put("typ", "JWT");
        return Jwts.builder()
                .setHeader(headerMap)
                .setClaims(map)
                .setExpiration(expireDate)
                .signWith(SignatureAlgorithm.RS256,key)
                .setIssuer(ISSUSER)
                .setSubject(SUBJECT)
                .setAudience(AUDIENCE)
                .compact();
    }

    /**
     * 公钥解析token
     *
     * @param token  用户请求中的token
     * @return
     * @throws Exception
     */
    private Jws<Claims> parserToken(String token, PublicKey key) {
        return Jwts.parser().setSigningKey(key).parseClaimsJws(token);
    }

    /**
     * 获取token中的用户信息
     *
     * @param token  用户请求中的令牌
     * @return 用户信息
     * @throws Exception
     */
    public Map<String, Object> getInfoFromToken(String token, PublicKey key) throws Exception {
        Jws<Claims> claimsJws = parserToken(token, key);
        return claimsJws.getBody();
    }

    /**
     * 生成jwt token
     */
    /*public String generateToken(long userId) {
        Date nowDate = new Date();
        //过期时间
        Date expireDate = new Date(nowDate.getTime() + expire * 1000);

        return Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setSubject(userId + "")
                .setIssuedAt(nowDate)
                .setExpiration(expireDate)
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }*/

    /*public Claims getClaimByToken(String token) {
        try {
            return Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            log.debug("validate is token error ", e);
            return null;
        }
    }*/

    /**
     * token是否过期
     *
     * @return true：过期
     */
    public boolean isTokenExpired(Date expiration) {
        return expiration.before(new Date());
    }

    public long getExpire() {
        return expire;
    }

    public void setExpire(long expire) {
        this.expire = expire;
    }

    public String getHeader() {
        return header;
    }

    public void setHeader(String header) {
        this.header = header;
    }
}
